
<template>
  <view class="order_page">
    <view class="status_type">
      <view class="type_item" @click.stop="changeType(5)">
        <text class="type_text" :class="statusType === 5 ? 'current' : ''"
          >全部
        </text>
      </view>
      <view class="type_item" @click.stop="changeType(0)">
        <text class="type_text" :class="statusType === 0 ? 'current' : ''"
          >待付款
        </text>
      </view>
      <view class="type_item" @click.stop="changeType(1)">
        <text class="type_text" :class="statusType === 1 ? 'current' : ''"
          >待发货
        </text>
      </view>
      <view class="type_item" @click.stop="changeType(2)">
        <text class="type_text" :class="statusType === 2 ? 'current' : ''"
          >待收货
        </text>
      </view>
      <view class="type_item" @click.stop="changeType(3)">
        <text class="type_text" :class="statusType === 3 ? 'current' : ''"
          >退款/售后
        </text>
      </view>
    </view>

    <order-empty v-if="!listData.total" />
    <view v-else class="order_list">
      <view
        class="order_card"
        v-for="item in listData.list"
        :key="item.id"
        @click.stop="onViewDetail(item)"
      >
        <view class="order-logistics">
          <view class="order-tag">快递配送</view>
          <view class="order-address">{{
            item.receiverProvince +
            item.receiverCity +
            item.receiverRegion +
            item.receiverDetailAddress
          }}</view>
          <view class="order-status">{{
            orderStatusFilter(item.orderStatus)
          }}</view>
        </view>

        <view class="order-goods">
          <view class="flex" v-for="item in item.items" :key="item.id">
            <view
              class="goods-cover cover"
              :style="{ backgroundImage: `url(${item.productImageUrl})` }"
            ></view>
            <view class="flex" style="width: 100%">
              <view class="goods-name line-clamp-2">
                {{ item.productName }}
              </view>
              <view class="order-total">
                <view class="goods-price">¥{{ item.productSkuPrice }}</view>
                <view class="goods-count">x{{ item.productSkuQuantity }}</view>
              </view>
            </view>
          </view>
          <view class="flex items-end justify-end leading-none mt-16px text-s">
            <label class="mr-5px">共{{ item.items.length || 0 }}件商品</label
            >实付款：
            <view class="price">
              <view class="master" style="font-weight: normal">{{
                cal.jia(item.finalAmount, item.freightAmount)
              }}</view>
              <!-- <label>.00</label> -->
            </view>
          </view>

          <view class="order-handle">
            <button
              class="action_btn"
              v-if="item.orderStatus === 2"
              @click.stop="
                linkTo('/personalPages/order/logisticsDetail?id=' + item.id)
              "
            >
              查看物流
            </button>
            <button
              class="action_btn primary"
              v-if="item.orderStatus === 2"
              @click.stop="ConfirmReceive(item.id)"
            >
              确认收货
            </button>
            <button
              class="action_btn primary"
              v-if="item.orderStatus === 0 || item.orderStatus === 6"
              @click.stop="toPay(item.id)"
            >
              立即付款
            </button>
            <button
              class="action_btn"
              v-if="item.orderStatus === 0 || item.orderStatus === 6"
              @click.stop="cancel(item)"
            >
              取消订单
            </button>
            <button
              class="action_btn delete"
              v-if="
                item.orderStatus === 3 ||
                item.orderStatus === 4 ||
                item.orderStatus === 5
              "
              @click.stop="deleOrder(item.id)"
            >
              删除订单
            </button>
          </view>
        </view>
      </view>

      <uni-load-more
        class="loadMore"
        v-if="listData.list.length !== 0"
        :status="loadingStatus"
        :content-text="contentText"
        @click.stop="scrollChange"
      />
    </view>
  </view>
</template>
  
<script setup>
import OrderEmpty from "@/components/empty-order";
import UniLoadMore from "@/components/uni-load-more/uni-load-more";

import { ref, defineProps, watch } from "vue";
import { onLoad, onShow, onHide, onReachBottom } from "@dcloudio/uni-app";
import { message, debounce, orderStatusFilter } from "@/utils/utils";
import { cal } from "@/utils/cal";
import {
  GetOrderList,
  wxOrderPurchase,
  cancelOrder,
  deleteOrder,
  receiveConfirm,
} from "@/services/mall";

const props = defineProps({
  currentType: {
    type: Number,
    default: 0,
  },
});

const statusType = ref(5); // 0待付款，1待发货，2待收货，3已完成。不传为全部
const pagination = ref({
  orderStatus: "",
  pageNum: 1,
  pageSize: 10,
});
const listData = ref({
  total: 0,
  list: [],
});
const contentText = ref("加载更多");
const loadingStatus = ref("more");

const changeType = (type) => {
  if (statusType.value === type) return;
  statusType.value = type;
  pagination.value.pageNum = 1;
  getList();
};

onLoad(() => {});
onShow(() => {
  pagination.value.pageNum = 1;
  pagination.value.pageSize = 10;
  getApp().accessLogAdd();
  getList();
});
onHide(() => {
  pagination.value.pageNum = 1;
});

onReachBottom(() => {
  console.log("到底啦~~~~~~~~~~~");
  scrollChange();
});

const linkTo = (url) => uni.navigateTo({ url });

const getList = async () => {
  loadingStatus.value = "more";
  contentText.value = "加载更多";
  let params = pagination.value;
  if (statusType.value === 5) {
    params.orderStatus = "";
  } else {
    params.orderStatus = statusType.value;
  }
  const res = await GetOrderList(params);
  listData.value = res.data;
  if (listData.value.list.length === listData.value.total) {
    loadingStatus.value = "noMore";
    contentText.value = "没有更多";
  }
};
watch(
  () => props.currentType,
  () => {
    console.log("监听porps", props.currentType);
    if (props.currentType === 0) {
      getList();
    }
  },
  {
    immediate: true, // 这个属性是重点啦
  }
);

const scrollChange = async () => {
  if (listData.value.list.length === listData.value.total)
    return (loadingStatus.value = "noMore"), (contentText.value = "没有更多");

  loadingStatus.value = "loading";
  contentText.value = "加载中";
  pagination.value.pageNum++;
  const res = await GetOrderList(pagination.value);
  if (res?.code === 200) {
    listData.value.list = listData.value.list.concat(res.data.list);
    if (listData.value.list.length === listData.value.total) {
      loadingStatus.value = "noMore";
      contentText.value = "没有更多";
    } else {
      loadingStatus.value = "more";
      contentText.value = "加载更多";
    }

    console.log(listData.value);
  }
};

const onViewDetail = (item) => {
  uni.navigateTo({ url: "/personalPages/order/detail?id=" + item.id });
};
// 立即支付
const toPay = async (id) => {
  getApp().emdlz(
    "track",
    "event",
    "store_page",
    "click",
    `order_pay_${id}`,
    `${props.detail.finalAmount}`
  );
  getApp()
    .sr()
    .track("custom_order", {
      order: {
        order_id: props.detail.id,
        order_time: Date.now(),
        order_status: "pay",
      },
      sub_orders: [
        {
          sub_order_id: props.detail.id,
          order_amt: props.detail.totalAmount,
          pay_amt: props.detail.finalAmount,
        },
      ],
      // more...
    });

  const res = await wxOrderPurchase({ id, appId: process.env.WXAPPID });
  if (res?.code === 200) {
    uni.requestPayment({
      provider: "wxpay", //支付类型-固定值
      timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
      nonceStr: res.data.nonceStr, // 随机字符串
      package: res.data.package, // 固定值
      signType: res.data.signType, //固定值
      paySign: res.data.paySign, //签名
      success: async function (res) {
        console.log("success:" + JSON.stringify(res));

        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: props.detail.id,
              order_time: Date.now(),
              order_status: "payed",
            },
            sub_orders: [
              {
                sub_order_id: props.detail.id,
                order_amt: props.detail.totalAmount,
                pay_amt: props.detail.finalAmount,
              },
            ],
            // more...
          });
        await message("支付成功", 1000);
        uni.reLaunch({
          url: "/pages/paySuccess/index",
        });
      },
      fail: function (err) {
        console.log("fail:" + JSON.stringify(err));
        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: props.detail.id,
              order_time: Date.now(),
              order_status: "cancel_pay",
            },
            sub_orders: [
              {
                sub_order_id: props.detail.id,
                order_amt: props.detail.totalAmount,
                pay_amt: props.detail.finalAmount,
              },
            ],
            // more...
          });
        uni.showModal({
          title: "确定取消支付吗？",
          content: "120分钟内未付款，订单将自动关闭，请尽快付款哦！",
          cancelText: "稍后付款",
          confirmText: "继续付款",
          success: function (res) {
            if (res.confirm) {
              console.log("用户点击确定");
              toPay(id);
            } else if (res.cancel) {
              console.log("用户点击取消");
              message("取消支付");
            }
          },
        });
      },
    });
  } else {
    message(res.message);
  }
};
// 取消订单
const cancel = debounce(
  async (item) => {
    getApp().emdlz(
      "track",
      "event",
      "store_page",
      "click",
      `order_cancel_${item.id}`,
      `${item.finalAmount}`
    );
    const res = await cancelOrder({ id: item.id });
    if (res?.code === 200) {
      getApp()
        .sr()
        .track("custom_order", {
          order: {
            order_id: item.id,
            order_time: Date.now(),
            order_status: "cancel_give_order",
          },
          sub_orders: [
            {
              sub_order_id: item.id,
              order_amt: item.totalAmount,
              pay_amt: item.finalAmount,
            },
          ],
          // more...
        });
      await message("取消成功", 2000);
      getList();
    } else {
      message(res.message);
    }
  },
  500,
  false
);
// 删除订单
const deleOrder = debounce(
  (id) => {
    uni.showModal({
      content: "确定是否删除此订单？",
      success: async function (res) {
        if (res.confirm) {
          console.log("用户点击确定");
          const res = await deleteOrder(id);
          if (res?.code === 200) {
            await message("删除成功", 2000);
            getList();
          } else {
            message(res.message);
          }
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  500,
  false
);
// 确认收货
const ConfirmReceive = debounce(
  async (id) => {
    const res = await receiveConfirm({ id: id });
    if (res?.code === 200) {
      await message("确认收货", 2000);
      getList();
    } else {
      message(res.message);
    }
  },
  500,
  false
);
</script>
  
<style lang="less" scoped>
@import "@/static/css/theme.less";
.order_page {
  width: 375px;
  min-height: 100vh;
  background-color: #f0f1f3;
  overflow-y: auto;
  box-sizing: border-box;
  padding-top: 65px;
  font-size: 14px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  .status_type {
    position: relative;
    display: flex;
    justify-content: space-between;
    width: 375px;
    height: 32px;
    box-sizing: border-box;
    padding: 0 12px;

    .type_item {
      background-color: #fff;
      border-radius: 4px;
      text-align: center;

      .type_text {
        width: 64px;
        height: 32px;
        display: block;
        line-height: 32px;
        font-weight: 400;
        color: #a9a9a9;
      }
    }
  }
  .current {
    border: 1px solid #0058c6;
    border-radius: 4px;
    color: #0058c6 !important;
  }
  .order_list {
    box-sizing: border-box;
    padding: 12px;
    overflow: hidden;
    .order_card {
      width: 351px;
      min-height: 188px;
      background-color: #ffffff;
      border-radius: 2px;
      box-sizing: border-box;
      padding: 10px 8px;
      margin-bottom: 9px;
    }
    .order_card:last-child {
      margin-bottom: 0;
    }
    .order-logistics {
      height: 22px;
      display: flex;
      align-items: center;
      font-weight: bold;
      line-height: 1;
      padding-bottom: 11px;
      border-bottom: 1px solid #f2f2f2;
      .order-tag {
        width: 58px;
        height: 22px;
        margin-right: 6px;
        background-color: #e8f0fb;
        font-size: 12px;
        color: #0058c6;
      }

      .order-address {
        flex: 1;
        font-weight: 500;
        color: #232323;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .order-status {
        margin-left: 4px;
        font-weight: 500;
        color: #0058c6;
      }
    }
    .order-goods {
      padding-top: 11px;

      .goods-cover {
        width: 68px;
        min-width: 68px;
        height: 68px;
        border-radius: 4px;
        background-color: rgba(0, 0, 0, 0.2);
      }

      .goods-name {
        padding: 0 12px 0 8px;
        box-sizing: border-box;
        font-size: 14px;
        flex: 1;
        height: 40px;
        font-weight: 500;
      }

      .order-total {
        color: #353535;
        text-align: right;
        font-size: 14px;

        .goods-count {
          font-size: 12px;
          color: #818181;
          line-height: 1;
          margin-top: 5px;
        }
      }

      .order-handle {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        background-color: white;
        box-sizing: border-box;
        padding: 10px 0;

        .action_btn {
          margin: 0;
          margin-left: 12px;
          width: 80px;
          height: 24px;
          line-height: 22px;
          background: #ffffff;
          border: 1px solid #404040;
          border-radius: 24px;
          font-size: 13px;
          color: #363636;
          padding: 0;

          &::after {
            border: none;
          }
        }
        .primary {
          color: @primary-color;
          border-color: @primary-color;
        }
        .delete {
          color: @label-color;
          border-color: @label-color;
        }
      }
    }
  }
}
</style>
  
